<script setup lang="ts">
import { filterUser, AdminUpdateRank, UserSpecificID, AdminUpdateActive } from '../../../http/api'
import { onMounted, reactive, ref } from 'vue';
import pagination from '../../../components/pagination/index.vue'
import Cookies from 'js-Cookie';
import { ElMessage } from 'element-plus'
import reportDialog from './reportDialog.vue'
// import {Docxtemplater } from 'docxtemplater';
// import JSZip from 'jszip';
// import FileSaver from 'file-saver';

const super_admin = Cookies.get("super_admin")
onMounted(() => {
  filter(1)
})

const data = reactive({ data: [], total_pages: 0, total_records: 0 }) as any
interface User {
  id: number | undefined,
  tag: string,
  user_type?: number,
  index: number,
  is_active: boolean,
  number: number,
  mission: string,
  table: string,
  people: number,
  time: string
}

const filter = (val: number) => {
  paginationFlag.value = true
  filterUser(val, 5).then((res: any) => {
    res.data.map((x: any) => {
      if (x.super_admin) x.tag = "超级管理员"
      else if (x.high_admin) x.tag = "市级管理员"
      else if (x.mid_admin) x.tag = "区级管理员"
      else x.tag = "普通用户"
      x.active = x.is_active ? '正常' : "异常"
      x.number = (x.number == null) ? 1 : x.number
      x.mission = (x.mission == null) ? "入学测评" : x.mission
      x.table = (x.table == null) ? "抑郁自评量表(SDS)" : x.table
      x.people = (x.people == null) ? 7 : x.people
      x.time = (x.time == null) ? "2023-11-03 15:31:44" : x.time
    })
    data.data = res.data
    data.total_pages = res.total_pages
    data.total_records = res.total_records
  })
}

const user = reactive<User>({
id: undefined, tag: '', index: -1, is_active: true,
number: 0,
mission: '',
table: '',
people: 0,
time: ''
})

const resetUser = () => {
  queryUser.id = undefined
  queryUser.tag = ''
  queryUser.index = -1
  queryUser.user_type = undefined
}

//更改用户权限
const dialogVisible = ref<boolean>(false)
//子组件
const reportDialogRef=ref<any>()
//下载文件
const exportToWord=async()=> {
      const link = document.createElement("a");
      link.href = "./public/个人报告模板.docx";
      link.download = "个人报告.docx";   // 修改为你想要的文件名
      link.click();
};

  
const handleEdit = (index: number, row: any) => {
  user.index = index
  user.tag = row.tag
  user.id = row.id
  // dialogVisible.value = true
  reportDialogRef.value.open();
}
const type = (tag: string) => {
  switch (tag) {
    case "超级管理员": return "danger"
    case "市级管理员": return "warning"
    case "区级管理员": return "info"
    case "普通用户": return "success"
  }
}
const filterTag = (value: string, row: any) => {
  return row.tag === value
}
const confirm = () => {
  if (data.data[user.index].tag === user.tag) return
  else {
    let rank: string = ''
    switch (user.tag) {
      case "超级管理员": rank = "super_admin"; break
      case "市级管理员": rank = "high_admin"; break
      case "区级管理员": rank = "mid_admin"; break
      case "普通用户": rank = ""; break
    }
    AdminUpdateRank({ id: user.id as number, rank }).then((res: any) => {

      if (res.msg === 'user rank updated!') {
        data.data[user.index].tag = user.tag
        ElMessage.success("修改成功！")
      }
      dialogVisible.value = false
    })
  }
}


//注销用户
const dialogVisible2 = ref<boolean>(false)

const filterTag2 = (value: string, row: any) => {
  return row.active === value
}

const handleEdit2 = (index: number, row: any) => {
  user.index = index
  user.is_active = row.is_active
  user.id = row.id
  dialogVisible2.value = true
}
const UpdateActive = async () => {
  await AdminUpdateActive({ id: user.id as number }, user.is_active ? '0' : '1').then((res: any) => {
    if (res.code === 600015) {
      ElMessage.success("修改成功！")
      data.data[user.index].is_active = !data.data[user.index].is_active
      data.data[user.index].active = data.data[user.index].active === '正常' ? "异常" : "正常"
    }
  })
  dialogVisible2.value = false
}


const paginationFlag = ref<boolean>(true)


//根据id查用户
const queryUser = reactive<User>({
id: undefined, tag: '', index: -1, is_active: true,
number: 0,
mission: '',
table: '',
people: 0,
time: ''
})
const query = () => {
  if (queryUser.id === undefined) return
  UserSpecificID({ id: parseInt(queryUser.id as any) }).then((res: any) => {

    if (res.code === 611111) {
      if (res.user_info.super_admin) res.user_info.tag = "超级管理员"
      else if (res.user_info.high_admin) res.user_info.tag = "市级管理员"
      else if (res.user_info.mid_admin) res.user_info.tag = "区级管理员"
      else res.tag = "普通用户"

      data.data = []
      paginationFlag.value = false
      data.data[0] = res.user_info

    }
    else if (res.code === 600003) {
      paginationFlag.value = false
      data.data = []
    }
  })
}


const inputNum = (value: any) => {
  if (value == undefined) return;
  if (typeof value === 'number') return value
  return value
    .replace(/[^\d.]/g, "")
    .replace(/\.{2,}/g, ".")
    .replace(".", "$#$")
    .replace(/\./g, "")
    .replace("$#$", ".")
    .replace(/^\./g, "");
}
const isPersonFlag=ref(true)
</script>

<template>
  <div>
    <el-row>
      <el-col :span="20" :offset="2">
        <div class="dw-table-form" style="padding-left: 60px;">
          <el-form :inline="true" class="dw-form-inline" :model="user">
            <el-form-item label="任务名称:">
              <el-input placeholder="请输入任务名称"></el-input>
            </el-form-item>
            <el-form-item label="量表名称:">
              <el-input placeholder="请输入量表名称"></el-input>
            </el-form-item>

            <el-form-item style="margin-left: 20px;">
              <el-button @click="resetUser">重置</el-button>
              <el-button type="primary" @click="query"> 查询</el-button>
              <el-button type="primary" @click="filter(1)">查看所有</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="dw-table">
          <div class="dw-table-title">
          </div>
          <el-table stripe style="width: 100%" :data="data.data">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="#" prop="number" />
            <el-table-column label="任务名称" prop="mission" />
            <el-table-column label="量表名称" prop="table" />
            <el-table-column label="人数" prop="people" />
            <el-table-column label="时间" prop="time" />


            <el-table-column label="操作">
              <template #default="scope">              
                <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">报告预览</el-button>
                <reportDialog :isPersonFlag="isPersonFlag" ref="reportDialogRef"/>
                <br>
                <el-button size="small" type="primary" @click="exportToWord()">报告下载</el-button>
              </template>
            </el-table-column>

          </el-table>
          <div class="dw-pagination">
            <pagination :total="data.total_records" @current-change="filter" v-if="paginationFlag"
              :pageCount="data.total_pages" />

          </div>
        </div>
      </el-col>
    </el-row>
    <el-dialog v-model="dialogVisible" title="注销用户" width="30%">
      <div class="mb-2 flex items-center text-sm">
        <el-radio-group v-model="user.tag" class="ml-4">
          <el-radio label="超级管理员" size="large" v-if="super_admin === 'true'">超级管理员</el-radio>
          <el-radio label="市级管理员" size="large" v-if="super_admin === 'true'">市级管理员</el-radio>
          <el-radio label="区级管理员" size="large">区级管理员</el-radio>
          <el-radio label="普通用户" size="large">普通用户</el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible2" title="修改用户权限" width="30%">
      <div class="mb-2 flex items-center text-sm">
        是否{{ user.is_active ? '注销' : '恢复' }} id号为 {{ user.id }}的用户
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">否</el-button>
          <el-button type="primary" @click="UpdateActive">
            是
          </el-button>
        </span>
      </template>
    </el-dialog>


  </div>
</template>

<style scoped>
.dw-table-form {
  background-color: white;
  padding: 20px;
  margin-bottom: 20px;
}

.dw-table {
  background: white;
  padding: 20px;
}

.dw-table .dw-table-title {
  padding-bottom: 20px;
  border-bottom: 1px solid #f3f3f3;
}

.dw-table .dw-table-title h3 {
  padding: 0px;
  margin: 0px;
}

.el-form-item {
  margin-bottom: 0px;
}

.dw-dialog-form-item {
  margin-top: 20px;
}

.dw-pagination {
  padding-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>






<!-- 原代码 -->
<!-- <script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import datePicker from '../../../components/datetimepicker/index.vue'
import cascader from '../../../components/cascader/index.vue'
import { ReleaseCreate,ReleaseCityForSuperAdmin,ReleaseInfoForSuperAdmin,ReleaseCreateForSuperAdmin, ReleaseInfo, ACRM, ReleaseCity } from '../../../http/api'
import { ElMessage } from 'element-plus';
import { transformationGoTime } from '../../../utils/timeer'
import Bar from '../../../components/circularProgressBar/index.vue'
import Cookies from 'js-Cookie'

const form = reactive({ total: 1000, city_id: -1, city: '', begin_time: '',time: [] })

const change = (data: any) => {

    form.city_id = data[1][0]
    form.city = data[2][0]
}

const getTime = (data: string) => {

    form.begin_time = data
}



const releaseInfo = ref([]) as any
onMounted(() => {
    getReleaseInfo()
})
const getReleaseInfo = () => {
    if (checkIsSuperAdmin()){
        ReleaseInfoForSuperAdmin({city_id:1}).then((res: any) => {
        if (res.code === 611111) {
            releaseInfo.value = res.record
            for (let i = 0; i < releaseInfo.value.length; i++) {
                ACRM(releaseInfo.value[i].city_id).then((res: any) => {
                    releaseInfo.value[i].city = res.area
                })
            }
        }
        })
    }else {
        ReleaseInfo().then((res: any) => {
        if (res.code === 611111) {
            releaseInfo.value = res.record
            for (let i = 0; i < releaseInfo.value.length; i++) {
                ACRM(releaseInfo.value[i].city_id).then((res: any) => {
                    releaseInfo.value[i].city = res.area
                })
            }
        }
        })
    }
}

const open = () => {
    if (form.city_id === -1 || form.time[0] === '' || form.time[1] === '') return
    else if (checkIsSuperAdmin()) {
        ReleaseCreateForSuperAdmin({ total: form.total, city_id: form.city_id, begin_time: form.time[0], end_time: form.time[1] }).then((res: any) => {
            if (res.code === 611111) {
                ElMessage({
                    type: "success",
                    message: `已开放${form.city}的问卷填写！`
                })
                getReleaseInfo()
            }
            else if (res.code === 600003) {
                ElMessage({
                    type: "error",
                    message: `${form.city}已开放，请先删除当前开放许可，再重新开放`
                })
            }
        })
    }
    else {
        ReleaseCreate({ total: form.total, city_id: form.city_id, begin_time: form.time[0], end_time: form.time[1] }).then((res: any) => {
            if (res.code === 611111) {
                ElMessage({
                    type: "success",
                    message: `已开放${form.city}的问卷填写！`
                })
                getReleaseInfo()
            }
            else if (res.code === 600003) {
                ElMessage({
                    type: "error",
                    message: `${form.city}已开放，请先删除当前开放许可，再重新开放`
                })
            }
        })
    }
}

//判断是否为超级管理员
const checkIsSuperAdmin = () => {
    return Cookies.get("super_admin")
}


const list = ref() as any
const dialogVisible = ref(false)
const handleClose = (item: any) => {
    dialogVisible.value = true

    list.value = item
}
const del = () => {
    if (checkIsSuperAdmin()) {
        ReleaseCityForSuperAdmin(list.value.record).then((res: any) => {

        if (res.code === 611111) {

            releaseInfo.value.splice(releaseInfo.value.indexOf(list.value), 1)
        }
        })
        dialogVisible.value = false
    }else {
        ReleaseCity(list.value.record).then((res: any) => {

        if (res.code === 611111) {

            releaseInfo.value.splice(releaseInfo.value.indexOf(list.value), 1)
        }
        })
        dialogVisible.value = false
    }


}

const dialogVisible2 = ref(false)



const handleClick = (item: any) => {
    dialogVisible2.value = true

    list.value = item
}
</script>

<template>
    <el-row>
        <el-col :span="20" :offset="2">
            <div class="dw-table-form" style="padding-left: 60px;">
                <el-form class="dw-form-inline" :data="form">
                    <el-form-item label="已开放的许可" v-if="releaseInfo.length !== 0">
                        <el-tag v-for="tag in releaseInfo" style="margin:5px" :key="tag" class="mx-1 tag" closable
                            @click='handleClick(tag)' :disable-transitions="false" @close="handleClose(tag)">
                            {{ tag.city }}
                        </el-tag>

                    </el-form-item>
                    <el-form-item label="开放区域">
                        <cascader :msg="'city'" @change="change" :placeholder="'请选择地区'"></cascader>
                    </el-form-item>
                    <el-form-item label="开放数量">
                        <el-input-number :min="1000" :max="50000" v-model="form.total" />
                    </el-form-item>
                     <el-form-item label="开放时间">  //注释起
                        <datePicker @change="getTime" />
                    </el-form-item>                   //注释尾
                    <el-form-item label="选择开放时间">
                        <el-config-provider :locale="zhCn">
                            <el-date-picker type="datetimerange" value-format="YYYY-MM-DD hh:mm:ss" v-model="form.time"
                                :disabled-date="disabledDate" range-separator="~" start-placeholder="测评开始时间"
                                end-placeholder="测评结束时间 " />
                        </el-config-provider>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="open">开放许可</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-col>
    </el-row>
    <el-dialog v-model="dialogVisible" title="提示" width="30%">
        <div class="dialog">
            <span>是否删除<span>{{ list.city }}</span>的开放许可?</span>

        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">否</el-button>
                <el-button type="primary" @click="del">
                    是
                </el-button>
            </span>
        </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible2" width="30%">
        <div class="dialog">

            <div>
                <span>开放时间：</span>
                <span> {{ transformationGoTime(list.begin_time) }}</span>

            </div>
            <div>
                <span>截止时间：</span>
                <span> {{ transformationGoTime(list.end_time) }}</span>

            </div>
             <div>{{ list }}</div>    //一行注释
            <Bar :percentNum="list.submitted !== 0 ? (list.submitted / list.total) * 100 : 0">
                <div style="display:flex;  flex-direction: column;align-items: center;color:#fff">
                    <div><span>{{ list.submitted }}</span><span style="color:rgb(57, 156 , 172)">/{{ list.total }}</span>
                    </div>
                    <div style="font-size:12px;margin-top: 10px;">提交人数</div>
                </div>

            </Bar>
        </div>

    </el-dialog>
</template>

<style lang="scss" scoped>
.dw-table-form {
    background-color: white;
    padding: 20px;
    margin-bottom: 20px;
    width: 500px;
    
    .tag {
        margin: 5px;
        cursor: pointer;
    }
}

.dialog {
    margin: 5px;
    font-size: 16px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    >span {
        margin: 5px;

        >span {
            color: red;

        }
    }

    >div {
        margin: 5px;
    }
}
</style> -->